package com.yonyougov.cruxtestcase.testcase.allbasequery;

import com.yonyougov.cruxtestcase.component.CommonLogin;
import com.yonyougov.cruxtestcase.component.CommonQuery;
import com.yonyougov.cruxtestcase.component.ZWCDInvoke;
import com.yonyougov.cruxtestcase.dto.BaseResponseDto;
import com.yonyougov.cruxtestcase.dto.BaseTestReqDto;
import com.yonyougov.cruxtestcase.testcase.allbasequery.dto.ServiceEntityDto;
import com.yonyougov.cruxtestcase.testcase.allbasequery.vo.EurekaAppResult;
import com.yonyougov.cruxtestcase.testcase.allbasequery.vo.EurekaAppVo;
import com.yonyougov.cruxtestcase.testcase.allbasequery.vo.EurekaInstanceVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommonQueryService {
    private final ZWCDInvoke zwcdInvoke;
    private final RestTemplate restTemplate;
    private final CommonLogin commonLogin;
    private final CommonQuery commonQuery;
    public CommonQueryService(ZWCDInvoke zwcdInvoke, RestTemplate restTemplate, CommonLogin commonLogin, CommonQuery commonQuery) {
        this.zwcdInvoke = zwcdInvoke;
        this.restTemplate = restTemplate;
        this.commonLogin = commonLogin;
        this.commonQuery = commonQuery;
    }

    /**
     * 通用查询
     */
    public List<BaseResponseDto> commonQuery(BaseTestReqDto baseDto) {
        List<BaseResponseDto> baseResponseDtos = new ArrayList<>();
        //获取当前环境注册中心的地址
        String baseUrl = zwcdInvoke.getBaseUrl(baseDto.getEnvName());
        if (!StringUtils.isEmpty(baseUrl)) {
            String token = commonLogin.getToken(baseUrl, baseDto.getUser(), baseDto.getPassword());
            if (StringUtils.isNotBlank(token)) {
                //查询当前环境注册中心上注册的平台服务名称
                List<String> cruxServiceNames = getCruxEurekaInstances(baseDto,baseUrl);
                for (String cruxServiceName : cruxServiceNames) {
                    if(cruxServiceName.matches("crux-tm") || cruxServiceName.matches("crux-tm-cluster") || cruxServiceName.matches("crux-tm-job")){
                        continue;
                    }
                    //调用metedata 接口获取当前服务的所有实体类
                    String entityUrl = baseUrl + "/crux-metadata/api/metadata/services?serviceId=" + cruxServiceName;
                    List<ServiceEntityDto> serviceEntityDtoList = commonQuery.getEntityByServiceId(entityUrl, token);
                    for (ServiceEntityDto serviceEntityDto : serviceEntityDtoList) {
                        if(null == serviceEntityDto.getName()){
                            continue;
                        }
                        // 临时过滤
//                        if("elementmetadataitem".equalsIgnoreCase(serviceEntityDto.getName())){
//                            continue;
//                        }
                        //调用通用接口
                        String commonQueryUrl = baseUrl + "/"+cruxServiceName+"/api/" + serviceEntityDto.getName().toLowerCase();
                        try{
                            ResponseEntity responseEntity = commonQuery.commonQuery1(commonQueryUrl, token);
//                            if(responseEntity.getStatusCode() != HttpStatus.OK){
//                                BaseResponseDto baseResponseDto = new BaseResponseDto();
//                                baseResponseDto.setSuccess(false);
//                                baseResponseDto.setErrorMsg("调用接口"+commonQueryUrl+"失败.原因: "+responseEntity.getBody());
//                            }
                        }catch (Exception e){
                            BaseResponseDto baseResponseDto = new BaseResponseDto();
                            baseResponseDto.setSuccess(false);
                            baseResponseDto.setErrorMsg("调用接口"+commonQueryUrl+"失败.原因: "+e.getMessage());
                            baseResponseDtos.add(baseResponseDto);
                        }
                    }
                }
            } else {
                BaseResponseDto baseResponseDto = new BaseResponseDto();
                baseResponseDto.setSuccess(false);
                baseResponseDto.setErrorMsg("用户名或者密码错误，获取token失败");
                baseResponseDtos.add(baseResponseDto);
            }
        }
        return baseResponseDtos;
    }

    /**
     * 查询当前环境注册中心上注册的平台服务名称
     */
    private List<String> getCruxEurekaInstances(BaseTestReqDto baseDto, String baseUrl) {
        List<String> result = new ArrayList<>();
        String eurekaUrl = baseUrl + "/eureka";
        //获取实例
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept","application/json");
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<EurekaAppResult> responseEntity = restTemplate.exchange(eurekaUrl + "/apps", HttpMethod.GET, entity, EurekaAppResult.class);
        if (responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.hasBody()) {
            EurekaAppResult body = responseEntity.getBody();
            for (EurekaAppVo eurekaAppVo: body.getApplications().getApplication()) {
                if(eurekaAppVo.getName().toLowerCase().contains("crux")){
                    for (EurekaInstanceVo eurekaInstanceVo: eurekaAppVo.getInstance()) {
                        if(eurekaInstanceVo.getStatus().equalsIgnoreCase("UP")){
                           result.add(eurekaAppVo.getName().toLowerCase());
                        }
                    }
                }
            }
        }
        return result;
    }
}
